package com.xuecheng.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.netflix.client.VipAddressResolver;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CompanyAuditDto;
import com.xuecheng.commons.model.dto.CompanyDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CompanyVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.system.domain.Company;
import com.xuecheng.system.mapper.CompanyMapper;
import com.xuecheng.system.service.CompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.time.Duration;
import java.util.*;

/**
 * <p>
 * 教育机构 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    //机构资料提交
    @Override
    public ResponseResult postCompany(CompanyDto dto) {
        //检验参数
       /* if (StrUtil.isBlank(dto.getBriefIntro())//简介
                //||StrUtil.isBlank(dto.getAddress())//机构地址
                ||StrUtil.isBlank(dto.getBusinessPic())|| StrUtil.isBlank(dto.getBusinessRegistNo())//营业执照,注册号
                //||new Date().before(dto.getBusinessTerm())
                || StrUtil.isBlank(dto.getEmail())//营业执照有效期,邮箱
                ||StrUtil.isBlank(dto.getHandPhotos())||StrUtil.isBlank(dto.getIntro())//手持照片,机构简介
                ||StrUtil.isBlank(dto.getLinkname()) ||StrUtil.isBlank(dto.getLogo())//申请人名称,机构logo
                ||StrUtil.isBlank(dto.getMainCategory())|| StrUtil.isBlank(dto.getName())//主营类目,名称
                ||StrUtil.isBlank(dto.getPhone())||StrUtil.isBlank(dto.getPromiseLetter())//联系方式,承诺书
                ||StrUtil.isBlank(dto.getTitle())||StrUtil.isBlank(dto.getTrademarkPic())//机构名称,商标注册证
                ||StrUtil.isBlank(dto.getVerifyCode())//手机验证码
                //|| StrUtil.isBlank(dto.getVerifyKey())//手机验证标识符
        ){
            throw new BusinessException(ErrorCode.PARAMSERROR);//参数错误
        }*/
        //比较验证码是否正确
        //取出redis
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:" + dto.getPhone());
        //比较验证码
        if (!StrUtil.equals(dto.getVerifyCode(),codeFromRedis)) {
            throw new BusinessException(ErrorCode.NOTTOKEN);//token不合法
        }
        //查询数据库是否存在此机构
        LambdaQueryWrapper<Company> qw = new LambdaQueryWrapper<>();
        qw.eq(Company::getPhone,dto.getPhone());
        Company one = this.getOne(qw);
        Company company = BeanHelper.copyProperties(dto, Company.class);
        if (one != null){//如果数据库存在则提示错误
            throw new BusinessException(ErrorCode.ADDEERROR);//数据保存失败
        }else{
            //如果没有则新建机构
            //补全字段信息
            company.setCreateDate(DateUtil.date());//创建时间
            company.setPhone(dto.getPhone());
            company.setApprovalStatus(CourseConstants.INSTIUTIONS_TO_AUDIT);//202002
            company.setOrgType("c");
            company.setMainCategory(dto.getMainCategory());
            //保存数据库
            this.save(company);
        }

        // 存入redis
        redisTemplate.opsForValue().set("phone:"+dto.getPhone(), dto, Duration.ofDays(1));
        // 清除redis中验证码
        redisTemplate.delete("code:" + dto.getPhone());
        //返回机构结果
        Map map = new HashMap();
        map.put("companyId", company.getId());
        return ResponseResult.okResult(map);
    }



    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CompanyService companyService;


    //机构/个人组织列表查询
    @Override
    public ResponseResult findByPage(PageRequest request,  CompanyDto dto) throws IOException {

        //构建分页
        Page<Company> page = new Page<>(request.getPageNo(),request.getPageSize());
        //构建条件
        LambdaQueryWrapper<Company> qw = new LambdaQueryWrapper<>();
        //获取状态
        List<String> strings = Arrays.asList(dto.getApprovalStatus().split(","));

        //机构列表查询状态,审核通过/未审核/审核失败202003,202002,202001
        if (strings.contains("202003")){
            qw.eq(Company::getApprovalStatus,CourseConstants.INSTIUTIONS_THROUGH);
        }else {
            //机构审核列表查询状态,未审核/审核失败
            qw.ne(Company::getApprovalStatus,CourseConstants.INSTIUTIONS_THROUGH);//除了审核通过的
        }
        //qw.in(ObjectUtil.isNotEmpty(strings),Company::getApprovalStatus,strings);

        //执行分页查询
        page = this.page(page,qw);
        /*List<Company> list = this.list();
        Long counts = Long.valueOf(list.size());//todo*/

        List<Company> companyList = page.getRecords();
        List<CompanyVo> voList = BeanHelper.copyWithCollection(companyList, CompanyVo.class);
        for (CompanyVo companyVo : voList) {
            companyVo.setCompanyId(companyVo.getId());
            companyVo.setPromiseLetter(companyVo.getPromiseLetter());
        }
        //返回分页结果
        //return PageResponseResult.okResult(5L,voList);
        return PageResponseResult.okResult(page.getTotal(),voList);
    }


    //机构审核
    @Override
    public ResponseResult approve(CompanyAuditDto dto ){
        //1.查询机构状态
        Company company = this.getById(dto.getCompanyId());
        //2.修改状态和内容
        company.setApprovalStatus(dto.getApprovalStatus());//审核状态
        company.setApprovalComment(dto.getApprovalComment());//审核意见
        company.setApprovalNums(company.getApprovalNums()+1);//审核次数
        company.setApprovalDate(DateUtil.date());//时间
        company.setApprovalPeople(AuthInfoHolder.getUserId().toString());//审核人
    //3.更新数据库
        this.updateById(company);
        return ResponseResult.okResult(true);
    }

    @Autowired
    private RestHighLevelClient client;
    //根据id查询机构
    @Override
    public ResponseResult findById(String companyId) throws IOException {
        //通过id查询
        Company company = this.getById(companyId);
        //Long companyId = AuthInfoHolder.getCompanyId();
        CompanyVo companyVo = BeanHelper.copyProperties(company, CompanyVo.class);
        companyVo.setTitle(company.getTitle());
        companyVo.setCompanyId(company.getId());
        companyVo.setName(company.getApprovalPeople());
        companyVo.setTrademarkPic(company.getTrademarkPic());
        return ResponseResult.okResult(companyVo);
    }
}
